package cn.chengpengper.im.platform.common.risk.rule.service.impl;

import cn.chengpengper.im.platform.common.model.enums.HttpCode;
import cn.chengpengper.im.platform.common.risk.rule.service.RuleChainService;
import cn.chengpengper.im.platform.common.risk.rule.service.base.BaseRuleChainService;
import cn.chengpengper.im.platform.common.risk.enums.RuleEnum;
import cn.chengpengper.im.platform.common.utils.XssUtils;
import cn.hutool.core.util.BooleanUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.util.Map;
import java.util.Objects;

/*@formatter:off*/

/**
 * ____________________
 * < 神兽护体，永无bug! >
 * --------------------
 *
 * @author huchengpeng
 * @version v1.0.0
 * @date 2024/11/23 20:47
 * @description Xss 检测拦截器
 */

/*@formatter:on*/

@Slf4j
@Component
public class XssRuleChainService extends BaseRuleChainService implements RuleChainService {

    @Value("${diy.im.rule.xssRule.enabled}")
    private Boolean xssRuleEnabled;

    @Value("${diy.im.rule.xssRule.order}")
    private Integer xssRuleOrder;

    @Override
    public HttpCode execute(HttpServletRequest request, Object handler) {
        if (BooleanUtil.isFalse(xssRuleEnabled)) {
            return HttpCode.SUCCESS;
        }
        Map<String, String[]> parameterMap = request.getParameterMap();
        for (String[] values : parameterMap.values()) {
            for (String value : values) {
                if (XssUtils.checkXss(value)) {
                    return HttpCode.XSS_PARAM_ERROR;
                }
            }
        }
        String body = getBody(request);
        if (XssUtils.checkXss(body)) {
            return HttpCode.XSS_PARAM_ERROR;
        }
        return HttpCode.SUCCESS;
    }

    private String getBody(HttpServletRequest request) {
        StringBuilder sb = new StringBuilder();
        try {
            BufferedReader reader = request.getReader();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (Exception e) {
            log.error("XssInterceptor.getBody | 获取请求体异常:{}", e.getMessage());
        }
        return sb.toString();
    }

    @Override
    public int getOrder() {
        return Objects.isNull(xssRuleOrder) ? RuleEnum.XSS.getCode() : xssRuleOrder;
    }

    @Override
    protected String getServiceName() {
        return RuleEnum.XSS.getMesaage();
    }
}
